<template>
  <div class="bigScreen">
    <div class="bigScreen-header">
      <Header :data="headerInfo" :warnList="warnList" :noticeList="noticeList"></Header>
    </div>
    <div class="bigScreen-main">
      <div :class="['bigScreen-main-left', isPackUp ? '' : 'active']">
        <div class="bigScreen-main-left-btn btn" @click="isPackUp = !isPackUp">
          <img src="@/assets/images/bigScreen/icon/right.png" alt="" v-show="isPackUp">
          <img src="@/assets/images/bigScreen/icon/left.png" alt="" v-show="!isPackUp">
        </div>
        <Left :workAreaList="workAreaList" :personEquipmentList="personEquipmentList" :areaId="areaId"
          :personEquipmentType="personEquipmentType"></Left>
      </div>
      <div class="bigScreen-main-center">
        <Center :data="mapInfo" :areaId="areaId"></Center>
      </div>
      <div :class="['bigScreen-main-right', isPackUp ? '' : 'active']">
        <div class="bigScreen-main-right-btn btn rotate" @click="isPackUp = !isPackUp">
          <img src="@/assets/images/bigScreen/icon/right.png" alt="" v-show="isPackUp">
          <img src="@/assets/images/bigScreen/icon/left.png" alt="" v-show="!isPackUp">
        </div>
        <MainRight :attendanceMonitorInfo="attendanceMonitorInfo" :bucketMonitor="bucketMonitor"
          :workMonitorInfo="workMonitorInfo" :gasMonitorInfo="gasMonitorInfo"></MainRight>
      </div>
    </div>
  </div>
</template>
<script>
import Header from '@/views/bigScreen/components/Header/index.vue';
import Left from '@/views/bigScreen/components/Left/index.vue';
import Center from '@/views/bigScreen/components/Center/index.vue';
import MainRight from '@/views/bigScreen/components/Right/index.vue';

import {
  getHeaderInfo,
  getWorkAreaList,
  getAttendanceMonitor,
  getBucketMonitor,
  getWorkMonitor,
  getGasMonitor,
  getMapCoordsInfo,
  getWarnList,
  getNotice,
  getMapEmployeeList,
} from '@/api/bigScreen.js';
import { getPersonEquipmentOptions } from './constant';

export default {
  name: "bigScreen",
  components: {
    Header,
    Left,
    Center,
    MainRight
  },
  data() {
    return {
      headerInfo: {},
      workAreaList: [],
      personEquipmentList: [],
      attendanceMonitorInfo: {},
      bucketMonitor: {},
      workMonitorInfo: {},
      gasMonitorInfo: {},
      mapInfo: {},
      areaId: '',
      personEquipmentType: 1, // 1-人员，2-车辆，3-环卫站
      timeoutId: null,
      pollInterval: 60 * 1000,
      warnList: [],
      noticeList: [],
      isPackUp: true,
    };
  },
  computed: {
    // 人员设备的请求
    personEquipmentRequest() {
      const options = getPersonEquipmentOptions();
      const currentOptions = options?.[this.personEquipmentType];
      return currentOptions?.request ?? "";
    },
  },
  watch: {
    isPackUp(val) {
      this.$bus.$emit('changeIsPackUp', val);
    },
  },
  async created() {
    this.onBus();
    await this.fetchData();
    if (this.workAreaList?.length) this.$bus.$emit('updateArea', this.workAreaList[0]?.id);

    // 优先聚焦到第一个环卫站，如果没有环卫站则保持原有的随机逻辑
    const platforms = this.mapInfo?.platforms;
    if (Array.isArray(platforms) && platforms.length > 0) {
      setTimeout(() => {
        this.$bus.$emit('changeMapView', { data: platforms[0], type: 'platforms', open: true });
      }, 1000);
    } else {
      // 如果没有环卫站数据，保持原有的随机聚焦逻辑
      const mapInfos = Object.keys(this.mapInfo).reduce((acc, key) => {
        const data = this.mapInfo[key];
        if (Array.isArray(data) && !!data.length) acc[key] = data;
        return acc;
      }, {});
      const mapInfoKeys = Object.keys(mapInfos);
      const mapInfoLen = mapInfoKeys.length;
      if (!mapInfoLen) return false;
      const index = Math.floor(Math.random() * mapInfoLen);
      const key = mapInfoKeys[index];
      const data = mapInfos[key];
      setTimeout(() => {
        this.$bus.$emit('changeMapView', { data: data[0], type: key, open: true });
      }, 1000);
    }
  },
  beforeDestroy() {
    this.stopTimeout();
    this.$bus.$off('updateArea', this.onChangeArea);
    this.$bus.$off('updatePersonEquipmentType', this.onChangePersonEquipmentType);
    this.$bus.$off('jumpWarn', this.onJumpWarn);
  },
  methods: {
    onBus() {
      this.$bus.$on('updateArea', this.onChangeArea);
      this.$bus.$on('updatePersonEquipmentType', this.onChangePersonEquipmentType);
      this.$bus.$on('jumpWarn', this.onJumpWarn);
    },
    fetchData() {
      return Promise.all([
        this.fetchHeader(),
        this.fetchWorkAreaList(),
        this.fetchPersonEquipment(),
        this.fetchAttendanceMonitor(),
        this.fetchBucketMonitor(),
        this.fetchWorkMonitor(),
        this.fetchGasMonitor(),
        this.fetchMapCoordsInfo(),
        this.fetchWarn(),
        this.fetchNotice(),
      ]).finally(() => {
        this.scheduleNextPoll();
        Promise.resolve('');
      })
    },
    scheduleNextPoll() {
      this.timeoutId = setTimeout(this.fetchData, this.pollInterval);
    },
    stopTimeout() {
      if (this.timeoutId) clearTimeout(this.timeoutId);
      this.timeoutId = null;
    },
    // 头部信息请求
    async fetchHeader() {
      try {
        const res = await getHeaderInfo();
        const data = res.data || {};
        this.headerInfo = data;
        Promise.resolve();
      } catch {
        Promise.reject();
      }
    },
    // 作业区域请求
    async fetchWorkAreaList() {
      try {
        const res = await getWorkAreaList();
        const data = res.data?.records ?? [];
        this.workAreaList = data;
        Promise.resolve();
      } catch {
        Promise.reject();
      }
    },
    // 人员设备请求
    async fetchPersonEquipment() {
      try {
        const res = await this.personEquipmentRequest(this.areaId);
        const data = res.data?.records ?? [];
        this.personEquipmentList = data;
        Promise.resolve();
      } catch {
        Promise.reject();
      }
    },
    // 考勤检测请求
    async fetchAttendanceMonitor() {
      try {
        const res = await getAttendanceMonitor();
        const data = res.data ?? {};
        this.attendanceMonitorInfo = data;
        Promise.resolve();
      } catch {
        Promise.reject();
      }
    },
    // 环卫站检测请求
    async fetchBucketMonitor() {
      try {
        const res = await getBucketMonitor();
        const data = res.data ?? {};
        const result = data.all;
        // this.bucketMonitor = result;
        this.bucketMonitor = data;
        Promise.resolve();
      } catch {
        Promise.reject();
      }
    },
    // 作业检测请求
    async fetchWorkMonitor() {
      try {
        const res = await getWorkMonitor();
        const data = res.data ?? {};
        this.workMonitorInfo = data;
        Promise.resolve();
      } catch {
        Promise.reject();
      }
    },
    // 气体检测请求
    async fetchGasMonitor() {
      try {
        const res = await getGasMonitor();
        const data = res.data ?? {};
        this.gasMonitorInfo = data;
        Promise.resolve();
      } catch {
        Promise.reject();
      }
    },
    // 地图信息请求
    async fetchMapCoordsInfo() {
      try {
        const res = await getMapCoordsInfo(this.areaId);
        const data = res.data ?? {};
        this.mapInfo = data;
        Promise.resolve();
      } catch {
        Promise.reject();
      }
    },
    async fetchWarn() {
      try {
        const res = await getWarnList();
        const data = res.data ?? [];
        this.warnList = data;
        Promise.resolve();
      } catch {
        Promise.reject();
      }
    },
    async fetchNotice() {
      try {
        const res = await getNotice();
        const data = res.rows ?? [];
        this.noticeList = data;
        Promise.resolve();
      } catch {
        Promise.reject();
      }
    },
    // 改变作业区域，影响人员设备和地图
    async onChangeArea(id) {
      this.areaId = id;
      try {
        this.stopTimeout();
        // 修改检测区域，人员设备和地图重新请求
        await this.fetchPersonEquipment();
        await this.fetchMapCoordsInfo();
      } finally {
        this.scheduleNextPoll();
      }
    },
    // 人员设备切换
    async onChangePersonEquipmentType(type) {
      this.personEquipmentType = type;
      try {
        this.stopTimeout();
        // 人员设备重新请求
        await this.fetchPersonEquipment();
      } finally {
        this.scheduleNextPoll();
      }
    },
    // 点击告警信息
    async onJumpWarn(item) {
      this.fetchWarn();
      const { areaId, toId, typeName } = item;
      try {
        this.areaId != areaId ? await this.onChangeArea(areaId) : await '';
        const data = this.mapInfo?.[typeName] ?? [];
        if (!data?.length) return this.$message.error('该区域暂没有当前类型的告警');
        const res = data.find(item => item.id == toId);
        if (!res) return this.$message.error('当前告警不存在该区域');
        setTimeout(() => {
          this.$bus.$emit('changeMapView', { data: res, type: typeName, open: true });
        }, 500)
      } catch (e) {
        this.$message.error(e);
      }
    },
  },
}
</script>

<style scoped lang="scss">
$headerHight: 74px;
$mainSideWidth: 20%;
$paddingX: 18px;

.bigScreen {
  width: 100%;
  height: 100%;
  background: url("~@/assets/images/bigScreen/bg.png") no-repeat center/cover;
  user-select: none;

  &>div {
    box-sizing: border-box;
  }

  &-header {
    position: relative;
    height: $headerHight;
    background: url("~@/assets/images/bigScreen/top/bg.png") no-repeat center/cover;
    padding: 0 $paddingX;
  }

  &-main {
    height: calc(100% - #{$headerHight});
    //padding: 0 $paddingX;
    position: relative;
    //display: flex;

    &>div {
      position: relative;
      height: 100%;
      transition: all 0.2s ease-in-out;
      z-index: 2;

      &>div {
        overflow: hidden;
      }

      &:not(.bigScreen-main-center) {
        position: absolute;
        top: 0;
        height: 100%;
        z-index: 99;
        //overflow: hidden;
      }

      .btn {
        width: 24px;
        height: 42px;
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        right: 0;
        color: #fff;
        cursor: pointer;
        z-index: 99;

        &.rotate {
          transform: rotate(180deg);
        }

        img {
          height: 100%;
          object-fit: cover;
        }
      }
    }

    &-left {
      width: 0;
      left: 0;

      &.active {
        width: $mainSideWidth;
      }

      .btn {
        right: -20px !important;
      }
    }

    &-right {
      width: 0;
      right: 0;

      &.active {
        width: $mainSideWidth;
      }

      .btn {
        left: -20px !important;
      }
    }
  }
}
</style>
